<!-- 对话管理页面 -->
<template>
	<div id="chat-history-manage-view">
		<!-- 搜索表单 -->
		<div class="search-section">
			<a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
				<a-form-item label="对话ID">
					<a-input v-model:value="searchParams.id" placeholder="输入对话ID" allow-clear style="width: 200px" />
				</a-form-item>
				<a-form-item label="消息类型">
					<a-select v-model:value="searchParams.messageType" placeholder="选择消息类型" allow-clear style="width: 120px">
						<a-select-option value="">全部</a-select-option>
						<a-select-option value="user">用户消息</a-select-option>
						<a-select-option value="ai">AI消息</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="应用ID">
					<a-input v-model:value="searchParams.appId" placeholder="输入应用ID" allow-clear style="width: 200px" />
				</a-form-item>
				<a-form-item label="用户ID">
					<a-input v-model:value="searchParams.userId" placeholder="输入用户ID" allow-clear style="width: 200px" />
				</a-form-item>
				<a-form-item>
					<a-space>
						<a-button type="primary" html-type="submit" :loading="loading">搜索</a-button>
						<a-button @click="resetSearch">重置</a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</div>

		<!-- 对话列表表格 -->
		<div class="table-section">
			<a-table
				:columns="columns"
				:data-source="dataList"
				:pagination="pagination"
				:loading="loading"
				@change="handleTableChange"
			>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'id'">
					<span class="chat-id">{{ record.id }}</span>
				</template>

				<template v-else-if="column.dataIndex === 'message'">
					<div class="message-cell">
						<a-tooltip :title="record.message">
							<span class="message-text">{{ truncateText(record.message, 50) }}</span>
						</a-tooltip>
					</div>
				</template>

				<template v-else-if="column.dataIndex === 'messageType'">
					<a-tag :color="getMessageTypeColor(record.messageType)" class="type-tag">
						{{ getMessageTypeText(record.messageType) }}
					</a-tag>
				</template>

				<template v-else-if="column.dataIndex === 'appId'">
					<div class="app-id-cell">
						<span class="app-id">{{ record.appId }}</span>
					</div>
				</template>

				<template v-else-if="column.dataIndex === 'userId'">
					<div class="user-id-cell">
						<span class="user-id">{{ record.userId }}</span>
					</div>
				</template>

				<template v-else-if="column.dataIndex === 'createTime'">
					<div class="time-cell">
						{{ formatTime(record.createTime) }}
					</div>
				</template>

				<template v-else-if="column.key === 'actions'">
					<a-space class="action-buttons">
						<a-button type="link" size="small" @click="viewFullMessage(record)" class="action-btn view-btn">
							查看详情
						</a-button>
						<a-button type="link" size="small" danger @click="deleteRecord(record.id)" class="action-btn delete-btn">
							删除
						</a-button>
					</a-space>
				</template>
			</template>
		</a-table>
		</div>

		<!-- 消息详情弹窗 -->
		<a-modal
			v-model:open="messageDetailVisible"
			title="消息详情"
			:footer="null"
			width="800px"
			class="message-detail-modal"
		>
			<div v-if="selectedRecord" class="message-detail">
				<a-descriptions title="基本信息" :column="2" bordered>
					<a-descriptions-item label="ID">{{ selectedRecord.id }}</a-descriptions-item>
					<a-descriptions-item label="消息类型">
						<a-tag :color="getMessageTypeColor(selectedRecord.messageType || '')">
							{{ getMessageTypeText(selectedRecord.messageType || '') }}
						</a-tag>
					</a-descriptions-item>
					<a-descriptions-item label="应用ID">{{ selectedRecord.appId }}</a-descriptions-item>
					<a-descriptions-item label="用户ID">{{ selectedRecord.userId }}</a-descriptions-item>
					<a-descriptions-item label="创建时间">{{ formatTime(selectedRecord.createTime || '') }}</a-descriptions-item>
					<a-descriptions-item label="更新时间">{{ formatTime(selectedRecord.updateTime || '') }}</a-descriptions-item>
				</a-descriptions>

				<div class="message-content-section">
					<h4>消息内容：</h4>
					<div class="message-content">
						<!-- 使用MessageItem组件渲染消息内容 -->
						<MessageItem
							:message="{
								id: selectedRecord.id,
								content: selectedRecord.message || '',
								role: selectedRecord.messageType === 'user' ? 'user' : 'ai',
								timestamp: selectedRecord.createTime
							}"
							:user-avatar="selectedRecord.messageType === 'user' && userInfo ? userInfo.userAvatar : undefined"
							:user-name="selectedRecord.messageType === 'user' ? (userInfo?.userName || '用户') : 'AI'"
						/>
					</div>
				</div>
			</div>
		</a-modal>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { listAllChatHistoryByPageForAdmin } from '@/api/chatHistoryController'
import { getUserVoById } from '@/api/userController'
import dayjs from 'dayjs'
import MessageItem from '@/components/app/message/MessageItem.vue'

// 搜索参数
const searchParams = reactive({
	id: undefined as number | undefined,
	message: undefined,
	messageType: undefined,
	appId: undefined as number | undefined,
	userId: undefined as number | undefined,
	sortField: undefined as string | undefined,
	sortOrder: undefined as string | undefined,
})

// 表格数据
const dataList = ref<API.ChatHistory[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
	current: 1,
	pageSize: 10,
	total: 0,
	showSizeChanger: true,
	showQuickJumper: false,
	pageSizeOptions: ['10', '20', '50'],
	showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 选中行
const selectedRowKeys = ref<number[]>([])
const rowSelection = {
	selectedRowKeys,
	onChange: (keys: number[]) => {
		selectedRowKeys.value = keys
	},
}

// 消息详情弹窗
const messageDetailVisible = ref(false)
const selectedRecord = ref<API.ChatHistory | null>(null)
const userInfo = ref<API.UserVO | null>(null)

// 表格列配置
const columns = [
	{
		title: '对话ID',
		dataIndex: 'id',
		align: 'center',
	},
	{
		title: '消息内容',
		dataIndex: 'message',
		align: 'center',
	},
	{
		title: '消息类型',
		dataIndex: 'messageType',
		align: 'center',
	},
	{
		title: '应用ID',
		dataIndex: 'appId',
		align: 'center',
	},
	{
		title: '用户ID',
		dataIndex: 'userId',
		align: 'center',
	},
	{
		title: '创建时间',
		dataIndex: 'createTime',
		align: 'center',
	},
	{
		title: '操作',
		key: 'actions',
		align: 'center',
	},
]

// 获取消息类型文本
const getMessageTypeText = (type: string) => {
	switch (type) {
		case 'user':
			return '用户消息'
		case 'ai':
			return 'AI消息'
		default:
			return type || '未知'
	}
}

// 获取消息类型颜色
const getMessageTypeColor = (type: string) => {
	switch (type) {
		case 'user':
			return 'blue'
		case 'ai':
		case 'assistant':
			return 'orange'
		default:
			return 'default'
	}
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
	if (!text) return '-'
	if (text.length <= maxLength) return text
	return text.substring(0, maxLength) + '...'
}

// 格式化时间
const formatTime = (time: string) => {
	if (!time) return '-'
	return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}



// 搜索
const doSearch = () => {
	pagination.current = 1
	loadData()
}

// 重置搜索
const resetSearch = () => {
	Object.assign(searchParams, {
		id: undefined,
		message: undefined,
		messageType: undefined,
		appId: undefined,
		userId: undefined,
		sortField: undefined,
		sortOrder: undefined,
	})
	pagination.current = 1
	loadData()
}

// 处理表格变化
const handleTableChange = (paginationInfo: any, filters: any, sorter: any) => {
	pagination.current = paginationInfo.current
	pagination.pageSize = paginationInfo.pageSize

	// 处理排序
	if (sorter.field) {
		searchParams.sortField = sorter.field
		searchParams.sortOrder = sorter.order === 'ascend' ? 'ascend' : 'descend'
	} else {
		searchParams.sortField = undefined
		searchParams.sortOrder = undefined
	}

	loadData()
}

// 查看完整消息
const viewFullMessage = async (record: API.ChatHistory) => {
	selectedRecord.value = record
	userInfo.value = null // 重置用户信息
	
	// 如果是用户消息且有用户ID，获取用户信息
	if (record.messageType === 'user' && record.userId) {
		try {
			const res = await getUserVoById({ id: record.userId })
			if (res.data.code === 0 && res.data.data) {
				userInfo.value = res.data.data
			}
		} catch (error) {
			console.error('获取用户信息失败:', error)
		}
	}
	
	messageDetailVisible.value = true
}

// 删除记录
const deleteRecord = (id: any) => {
	Modal.confirm({
		title: '确认删除',
		content: `确定要删除这条对话记录吗？此操作不可撤销。`,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		async onOk() {
			// 注意：这里需要后端提供删除接口
			// 暂时先提示功能未实现
			message.warning('删除功能暂未实现，需要后端提供相应接口')
		},
	})
}

// 加载数据
const loadData = async () => {
	loading.value = true
	try {
		const queryParams: any = {
			current: pagination.current,
			pageSize: pagination.pageSize,
		}

		// 只添加非空的搜索参数
		if (searchParams.id !== undefined) {
			queryParams.id = searchParams.id
		}
		if (searchParams.message && searchParams.message.trim()) {
			queryParams.message = searchParams.message.trim()
		}
		if (searchParams.messageType && searchParams.messageType.trim()) {
			queryParams.messageType = searchParams.messageType.trim()
		}
		if (searchParams.appId !== undefined) {
			queryParams.appId = searchParams.appId
		}
		if (searchParams.userId !== undefined) {
			queryParams.userId = searchParams.userId
		}
		if (searchParams.sortField && searchParams.sortOrder) {
			queryParams.sortField = searchParams.sortField
			queryParams.sortOrder = searchParams.sortOrder
		}

		const res = await listAllChatHistoryByPageForAdmin(queryParams)

		if (res.data.code === 0 && res.data.data) {
			dataList.value = res.data.data.records || []
			pagination.total = Number(res.data.data.totalRow) || 0
		} else {
			message.error('获取数据失败：' + (res.data.message || '未知错误'))
		}
	} catch (error) {
		console.error('获取数据失败:', error)
		message.error('获取数据失败')
	} finally {
		loading.value = false
	}
}

// 组件挂载时加载数据
onMounted(() => {
	loadData()
})


</script>

<style scoped>
#chat-history-manage-view {
}

:deep(.ant-table-thead > tr > th) {
	text-align: center;
}

:deep(.ant-table-tbody > tr > td) {
	text-align: center;
}

.chat-id {
	font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
	color: #1890ff;
	font-weight: 600;
	font-size: 13px;
	background: #f0f8ff;
	padding: 4px 8px;
	border-radius: 4px;
	display: inline-block;
}

.search-section {
	background: white;
	padding: 20px 24px;
	margin-bottom: 0;
	border-radius: 8px 8px 0 0;
	border: 1px solid #e8e8e8;
	border-bottom: none;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

	.search-form {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 16px;

		:deep(.ant-form-item) {
			margin-bottom: 0;
			margin-right: 0;
			display: flex;
			align-items: center;

			.ant-form-item-label {
				padding-right: 8px;
				width: auto;
				flex-shrink: 0;

				label {
					color: #333;
					font-size: 14px;
					font-weight: normal;
					margin-bottom: 0;
				}
			}

			.ant-form-item-control {
				min-height: auto;
			}
		}

		:deep(.ant-btn) {
			height: 32px;
			font-size: 14px;
			padding: 0 15px;
		}
	}
}

.table-section {
	background: white;
	border-radius: 0 0 8px 8px;
	border: 1px solid #e8e8e8;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	overflow: hidden;
}

/* 对话详情弹窗样式 */
.chat-detail-modal {
	:deep(.ant-modal-body) {
		padding: 0;
		max-height: 70vh;
		overflow-y: auto;
	}
}

.chat-detail-content {
	padding: 20px;
	background: #f8f9fa;
	
	/* 为MessageItem组件在弹窗中的显示进行样式调整 */
	:deep(.message-wrapper) {
		margin-bottom: 16px;
		
		&.user .message-bubble {
			max-width: 85%;
		}
		
		&.assistant .message-bubble {
			max-width: 90%;
		}
		
		.message-content {
			font-size: 14px;
			line-height: 1.6;
		}
		
		.message-time {
			font-size: 12px;
			opacity: 0.7;
		}
	}
}
</style>
